<html>
<head><title>Calculator</title></head>

<body>

<h1>Calculator</h1>
(4/5/2012 by Meng-Hsun Hsieh) <br />
Type an expression in the following box. (e.g., 1+2*3-4) <br />
	
<p>
<form method="GET">
<input type="text" name="expr">
<input type="submit" value="Calculate">
</form>
</p>

<ul>
<li>Only numbers and +, -, * and / operators are allowed.
<li>The calculator does not support parentheses.
<li>The calculator does not output PHP error messages.
<li>The calculator follows the standard operator precedence.
</ul>


<?php


if ($_GET["expr"] == "")
{
	echo "Please enter an expression";
	exit;
}

if (preg_match("*/0*", $_GET["expr"]))
{
	echo "Error: Division by 0: " . $_GET["expr"];
	exit;
}

if (!preg_match( "/\d+[+\-\*\/]\d+$/", $_GET["expr"]))
{
	echo "Error: Invalid expression: " . $_GET["expr"];
	exit;
}
else
{
	$val = eval('$result = ' . $_GET["expr"] . ";");

	if ($val === FALSE)
		echo "Error: Invalid input: " . $_GET["expr"];
	else
		echo $_GET["expr"] . " = " . $result;
}

?>



</body> 
</html>
